<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片区 -->
    <el-card class="box-card">
      <!-- 搜索和添加 -->
      <div slot="header" class="clearfix">
        <el-input
          placeholder="请输入内容"
          v-model="params.query"
          class="input-with-select"
          @blur="getuserlist"
          clearable
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click.enter="getuserlist"
          ></el-button>
        </el-input>
        <el-button type="primary" style="float: right" @click.native="add"
          >添加用户</el-button
        >
      </div>
      <!-- 内容表格 -->
      <el-table :data="formatDate" style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="create_time" label="创建日期" width="180">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮件"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 状态按钮 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @click.native="setstate(scope.row.id, scope.row.mg_state)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作">
          <!-- 编辑按钮 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="open(scope.row)"
            ></el-button>

            <!-- 分配按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                circle
                @click="getrole(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteuser(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="params.pagenum"
          layout=" prev, pager, next"
          :page-count="total"
        >
        </el-pagination>
      </div>
      <!-- 编辑用户框 -->
      <el-dialog title="编辑用户" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules" ref="form" status-icon>
          <!-- ref="ruleForm"获取数据，通过在el-form-item 添加属性prop="username"来定义规则 status-icon验证反馈图标 小圈圈-->
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              v-model="form.username"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="email"
            :label-width="formLabelWidth"
            prop="email"
          >
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="mobile"
          >
            <el-input
              v-model.number="form.mobile"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="edituser('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色框 -->
      <el-dialog title="分配角色" :visible.sync="dialogVisible" width="40%">
        <p>当前的用户:{{ user.username }}</p>
        <p>当前的角色:{{ user.role_name }}</p>
        <el-select v-model="rule" placeholder="请选择">
          <el-option
            v-for="item in rules"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          <!-- 这里的value才是真的保存到v-model="rule"的值，:label="item.roleName"只用于显示 -->
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setrole(user.id)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import moment from "moment";
export default {
  data() {
    // 判断用户名格式
    var checkusername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      setTimeout(() => {
        if (value.length < 3) {
          callback(new Error("用户名长度大于3个字符"));
        } else {
          callback();
        }
      }, 500);
    };
    // 判断号码格式
    var checkmobile = (rule, value, callback) => {
      if (value) {
        value = Number(value);
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error("请输入数字值"));
          } else {
            if (value.length) {
              callback(new Error("必需小于11位"));
            } else {
              callback();
            }
          }
        }, 500);
      } else {
        callback();
      }
    };
    // 判断邮箱格式
    var checkemail = (rule, value, callback) => {
      setTimeout(() => {
        let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (value) {
          if (!reg.test(value)) {
            callback(new Error("请正确输入邮箱"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }, 500);
    };
    return {
      rules: [], //角色列表
      user: {
        username: "",
        role_name: "",
        id:''
      },
      rule: "",
      dialogVisible: false, //分配角色编辑框开关
      oldemail: "",
      oldmobile: "",
      Id: 0,
      userlist: [],
      total: 0, //总页码
      params: {
        query: "", //条件查询
        pagenum: 1, //当前页码
        pagesize: 4, //每页显示条数
      },
      dialogFormVisible: false, //用户编辑框开关
      // 用户编辑框数据
      form: {
        id: "",
        username: "",
        email: "",
        mobile: 0,
      },
      formLabelWidth: "90px",
      // 定义判断规则
      rules: {
        username: [{ validator: checkusername, trigger: "blur" }],
        email: [{ validator: checkemail, trigger: "blur" }],
        mobile: [{ validator: checkmobile, trigger: "blur" }],
      },
    };
  },

  computed: {
    //    格式化日期
    formatDate() {
      for (let i = 0; i < this.userlist.length; i++) {
        let date = moment(this.userlist[i].create_time).format("MMMM Do YYYY");
        this.userlist[i].create_time = date + "";
      }
      return this.userlist;
    },
  },
  created() {
    this.getuserlist();
  },
  methods: {
    // 获取用户列表
    async getuserlist() {
      // 关键词和 默认获取列表
      if (
        Number(this.params.query) === 0 ||
        Number(this.params.query) + "" === NaN + ""
      ) {
        const { data: res } = await this.$http.get("users", {
          params: this.params,
        });
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: "没有找到",
            type: "error",
          });
        } else {
          if (res.data.total === 0) {
            return this.$message({
              showClose: true,
              message: "没有找到",
              type: "error",
            });
          } else {
            this.total = Math.ceil(res.data.total / 4);
            this.userlist = res.data.users;
          }
        }
      } else {
        // 根据id查询用户获取列表
        let id = Number(this.params.query);
        const { data: res } = await this.$http.get(`users/${id}`);
        if (res.meta.status === 400) {
          return this.$message({
            showClose: true,
            message: "没有找到",
            type: "error",
          });
        } else {
          console.log(res);
          this.userlist.splice(0, this.userlist.length);
          this.userlist.unshift(res.data);
        }
      }
    },
    // 获取当前页
    handleCurrentChange(val) {
      this.params.pagenum = val;
      this.getuserlist();
    },
    //   添加用户
    add() {
      this.$router.replace("/Adduser");
    },
    // 修改状态
    async setstate(id, type) {
      const { data: res } = await this.$http.put(`users/${id}/state/${type}`);
      if (res.meta.status === 200) {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: "success",
        });
      } else {
        this.$message({
          showClose: true,
          message: res.meta.msg,
          type: "error",
        });
      }
      console.log(res);
    },
    // 当打开编辑框获取用户信息
    open(user) {
      this.form.id = user.id;
      this.dialogFormVisible = !this.dialogFormVisible;
      this.form.username = user.username;
      this.form.email = user.email;
      this.form.mobile = user.mobile;
      this.oldmobile = user.mobile;
      this.oldemail = user.email;
    },
    // axios 编辑用户信息提交
    edituser(formName) {
      if (
        this.form.email === this.oldemail &&
        this.form.mobile === this.oldmobile
      )
        return (this.dialogFormVisible = !this.dialogFormVisible);
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `users/${this.form.id}`,
            this.form
          );
          console.log(res);
          if (res.meta.status === 200) {
            this.dialogFormVisible = !this.dialogFormVisible;
            this.getuserlist();
            return this.$message({
              showClose: true,
              message: res.meta.msg,
              type: "success",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 触发规则方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 删除用户
    deleteuser(user) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${user.id}`);
          if (res.meta.status === 200) {
            this.getuserlist();
          }
          this.$message({
            type: "success",
            message: res.meta.msg,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //获取角色
    async getrole(rule) {
      this.dialogVisible = !this.dialogVisible;
      this.user.username = rule.username;
      this.user.role_name = rule.role_name;
      this.user.id=rule.id
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status === 200) {
        this.rules = res.data;
        console.log(this.rules);
      } else {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: "error",
        });
      }
    },
   async setrole(id){
    const {data:res}=await  this.$http.put(`users/${id}/role`,{rid:this.rule})
    if(res.meta.status===200){
       this.dialogVisible = !this.dialogVisible;
       this.getuserlist()
      return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: "success",
        });
    }
    console.log(res);
    }
  },
};
</script>

<style scoped>
/* 搜索输入框 */
.input-with-select {
  width: 40%;
}
/* 卡片 */
.box-card {
  margin-top: 15px;
}
/* 分页 */
.block {
  margin-top: 15px;
}
</style>